from apps.merchant.coupon.baseViews import *


class CouponViewSet(BaseCouponViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = CouponDao().findAll().select_related('user')
        if params.get('status') == 'wait_use':
            _list = _list
        elif params.get('status') == 'has_use':
            _list = _list.order_by('-cancelTime')
        else:
            _list = _list
        return _list

    '''验证券'''
    @action(methods=['post'], detail=False)
    def checkCoupon(self, request):
        params = getRequestParams(request)
        _code = params.get('code')
        if not _code:
            return Response(response_modalMessage('code参数必填'))
        _coupons = CouponDao().findAll().filter(code=_code)
        if not _coupons.exists():
            return Response(response_modalMessage('优惠券不存在'))
        _coupon = _coupons.first()
        if request.user.lessee != _coupon.lessee:
            return Response(response_modalMessage('核销失败，非本店优惠券'))
        if _coupon.status == 'has_use':
            return Response(response_modalMessage('核销失败，优惠券已使用'))
        if _coupon.status == 'due':
            return Response(response_modalMessage('核销失败，优惠券已失效'))
        _couponData = CouponModelSerializer(_coupon).data
        return Response(response_success(_couponData))

    '''核销券'''
    @action(methods=['post'], detail=False)
    def cancelCoupon(self, request):
        params = getRequestParams(request)
        _code = params.get('code')
        _cancelType = params.get('cancelType')
        if not _code:
            return Response(response_modalMessage('code参数必填'))
        _coupons = CouponDao().findAll().filter(code=_code)
        if not _coupons.exists():
            return Response(response_modalMessage('优惠券不存在'))
        _coupon = _coupons.first()
        if request.user.lessee != _coupon.lessee:
            return Response(response_modalMessage('核销失败，非本店优惠券'))
        if _coupon.status == 'has_use':
            return Response(response_modalMessage('核销失败，优惠券已使用'))
        if _coupon.status == 'due':
            return Response(response_modalMessage('核销失败，优惠券已失效'))
        CouponDao().update(_coupon.id, {'status': 'has_use', 'cancelType': _cancelType, 'cancelTime': datetime.datetime.now()})
        return Response(response_success('核销成功'))